package com.sinsoft.monitorDemo.dao;

import java.util.ArrayList;
import java.util.List;

import redis.clients.jedis.Jedis;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.sinsoft.monitorDemo.entity.MemoryInfo;
import com.sinsoft.monitorDemo.util.JsonUtil;
import com.sinsoft.monitorDemo.util.RedisUtil;

public class MemInfoDao {
	/**
	 * 通过IP的到内存信息
	 * @param ip
	 * @param index
	 * @return
	 */
	public List<MemoryInfo> getMemInfoList(String ip){
		Jedis jedis = RedisUtil.getJedis();
		List<String> jsonList = jedis.lrange("StatusData_" + ip + "_MEM_latest", 0, -1);
		JsonArray jsonArray = null;
		JsonObject jsonObject = null;
		MemoryInfo memoryInfo = null;
		List<MemoryInfo> memoryInfoList = new ArrayList<MemoryInfo>();
		if (jsonList.size()>10) {
			for (int i = jsonList.size()-10; i < jsonList.size(); i++) {
				jsonArray = JsonUtil.JsonParse(jsonList.get(i));
				jsonObject = jsonArray.get(0).getAsJsonObject();
				memoryInfo = new MemoryInfo(jsonObject.get("mem_total").getAsDouble(), jsonObject.get("mem_used_per").getAsDouble(), 
						jsonObject.get("swap_total").getAsDouble(), jsonObject.get("swap_used_per").getAsDouble(), 
						jsonArray.get(1).getAsLong(),ip);
				memoryInfoList.add(memoryInfo);
			}	
		} else {
			for (int i = 1; i < jsonList.size(); i++) {
				jsonArray = JsonUtil.JsonParse(jsonList.get(i));
				jsonObject = jsonArray.get(0).getAsJsonObject();
				memoryInfo = new MemoryInfo(jsonObject.get("mem_total").getAsDouble(), jsonObject.get("mem_used_per").getAsDouble(), 
						jsonObject.get("swap_total").getAsDouble(), jsonObject.get("swap_used_per").getAsDouble(), 
						jsonArray.get(1).getAsLong(),ip);
				memoryInfoList.add(memoryInfo);
			}	
		}
		jedis.close();
		return memoryInfoList;		
	}
	/**
	 * 获得内存占用信息
	 * @param ip
	 * @return
	 */
	public MemoryInfo getNewMemInfo(String ip){
		Jedis jedis = RedisUtil.getJedis();
		MemoryInfo memoryInfo;
		try {
			List<String> jsonList = jedis.lrange("StatusData_" + ip + "_MEM_latest", -1, -1);
			JsonArray jsonArray = JsonUtil.JsonParse(jsonList.get(0));
			JsonObject jsonObject = jsonArray.get(0).getAsJsonObject();
			memoryInfo = new MemoryInfo(jsonObject.get("mem_total").getAsDouble(), jsonObject.get("mem_used_per").getAsDouble(), 
					jsonObject.get("swap_total").getAsDouble(), jsonObject.get("swap_used_per").getAsDouble(), 
					jsonArray.get(1).getAsLong(),ip);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return new MemoryInfo(null, null, null, null, null,null);
		}finally{
			jedis.close();			
		}
		return memoryInfo;		
	}
}
